package com.dykj.fireFighting.web.app;

import com.dykj.fireFighting.api.base.dev.entity.DevHisFiles;
import com.dykj.fireFighting.api.base.dev.entity.DevHisWaterZc;
import com.dykj.fireFighting.api.base.dev.entity.dto.DevHisWaterZcDto;
import com.dykj.fireFighting.api.base.dev.service.IDevHisFilesService;
import com.dykj.fireFighting.api.base.dev.service.IDevHisWaterService;
import com.dykj.fireFighting.api.base.dev.service.IDevHisWaterZcService;
import com.dykj.fireFighting.api.base.dev.service.IDevHisZcService;
import com.dykj.fireFighting.api.base.dev.vo.DevHisWaterZcVo;
import com.dykj.fireFighting.api.base.devHisResult.service.IDevHisResultService;
import com.dykj.fireFighting.api.base.effecttimesetting.service.IEffectiveTimeSettingService;
import com.dykj.fireFighting.api.base.effecttimesetting.vo.EffectiveTimeSettingVo;
import com.dykj.fireFighting.api.base.enterprise.entity.Enterprise;
import com.dykj.fireFighting.api.base.enterprise.service.IEnterpriseService;
import com.dykj.fireFighting.api.base.file.entity.DataFiles;
import com.dykj.fireFighting.api.socialUnit.devHis.service.IDevHisService;
import com.dykj.fireFighting.common.core.annotation.AutoLog;
import com.dykj.fireFighting.common.core.api.CommonResult;
import com.dykj.fireFighting.common.core.utils.DateUtil;
import com.dykj.fireFighting.common.core.utils.UUIDUtils;
import com.dykj.fireFighting.common.core.utils.ZcDataCleaning;
import com.dykj.fireFighting.common.core.vo.LoginUserVo;
import com.dykj.fireFighting.common.core.vo.PageVo;
import com.dykj.fireFighting.web.base.shiro.ShiroUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @Author: zly
 * @Description :
 * @Date: 2021-08-20
 */
@Slf4j
@Api(value = "VIEW接口", tags = {"VIEW接口"})
@RestController
@RequestMapping("/app/devHisWaterZc")
public class AppDevHisWaterZcController {

    @DubboReference
    private IDevHisWaterZcService devHisWaterZcService;
    @DubboReference
    private IEffectiveTimeSettingService effectiveTimeSettingService;
    @DubboReference
    private IDevHisWaterService devHisWaterService;
    @DubboReference
    private IDevHisZcService devHisZcService;
    @DubboReference
    private IDevHisFilesService devHisFilesService;
    @DubboReference
    private IEnterpriseService enterpriseService;
    @DubboReference
    private IDevHisResultService devHisResultService;
    @DubboReference
    private IDevHisService devHisService;
    /**
     * VIEW列表
     *
     * @return
     */
    @AutoLog(value = "VIEW-分页列表查询")
    @ApiOperation(value = "VIEW分页列表", notes = "VIEW分页列表")
    @GetMapping("/list")
    public CommonResult treeGrid(DevHisWaterZcDto devHisWaterZcDto) {
        LoginUserVo user = ShiroUtil.getUser();
        devHisWaterZcDto.setUnitId(user.getEnterpriseId().toString());

        String tableIndex=null;
        if(null !=devHisWaterZcDto.getSj() && StringUtils.isNotBlank(devHisWaterZcDto.getSj())){
            String[] strings = devHisWaterZcDto.getSj().split(",");
            String beginDate=strings[0];
            tableIndex=DateUtil.getWeek(beginDate);
        }else{
            tableIndex = DateUtil.getYearWeek();
        }
        HashMap<String, Object> map = new HashMap<>();
        int waterCount = devHisService.isExistTable("dev_his_water_" + tableIndex);
        int zcCount = devHisService.isExistTable("dev_his_zc_" + tableIndex);
        if(waterCount ==1 && zcCount == 1){
            map.put("water","dev_his_water_"+tableIndex);
            map.put("zc","dev_his_zc_"+tableIndex);
            PageVo<DevHisWaterZcVo> page = devHisWaterZcService.queryList(devHisWaterZcDto);
            for (int i = 0; i < page.getList().size(); i++) {
                if(StringUtils.isNotBlank(page.getList().get(i).getBjzt())){
                    page.getList().get(i).setBjztSm(ZcDataCleaning.dataCleaning(page.getList().get(i).getBjzt()));
                }
            }
            map.put("page",page);
        }
        return CommonResult.success(map);
    }

    /**
     * 获取VIEW信息
     */
    @AutoLog(value = "VIEW-获取VIEW信息")
    @ApiOperation(value = "获取VIEW信息", notes = "获取VIEW信息")
    @ApiImplicitParam(paramType = "path", name = "id", value = "主键ID", dataType = "Long", required = true)
    @GetMapping("/info/{id}")
    @RequiresPermissions("devHisWaterZc/info")
    public CommonResult<DevHisWaterZc> info(@PathVariable("id") Long id){
        DevHisWaterZc devHisWaterZc = devHisWaterZcService.getById(id);
        return CommonResult.success(devHisWaterZc);
    }


    /**
     * 修改VIEW信息
     */
    @AutoLog(value = "VIEW-修改VIEW信息")
    @ApiOperation(value = "修改VIEW信息", notes = "修改VIEW信息")
    @PostMapping("/update")
    public CommonResult update(@Valid @RequestBody DevHisWaterZc devHisWaterZc) {
        try {
            String tableName=devHisWaterZc.getTableName();
            if(StringUtils.isBlank(tableName)){
                return CommonResult.failed("表名为空");
            }
            DevHisWaterZc zc=devHisWaterZcService.queryByIdAndTable(devHisWaterZc.getId(),devHisWaterZc.getTableType(),tableName);
           if(null == zc){
            return CommonResult.failed("无此记录");
           }
            LoginUserVo user = ShiroUtil.getUser();
            devHisWaterZc.setFuhePersonId(user.getId().toString());
            devHisWaterZc.setFuhePerson(user.getLoginName());
            Enterprise enterprise = enterpriseService.getInfoByBindingCode(user.getBindingCode());
            //上传时间
            String uploadTime=null;
            if("1".equals(devHisWaterZc.getTableType())){
                uploadTime= zc.getUploadTime();
            }
            if("2".equals(devHisWaterZc.getTableType())){
                uploadTime=zc.getUpTime();
            }

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date parse = dateFormat.parse(uploadTime);

            EffectiveTimeSettingVo effectiveTimeSettingVo = effectiveTimeSettingService.isEffective(parse, "fireAlarm", enterprise.getId().toString());
            if(null !=effectiveTimeSettingVo){
                if(effectiveTimeSettingVo.getIsEffective()){
                    devHisWaterZc.setIsEffective(1);
                    devHisResultService.saveOne(6,user.getEnterpriseId().toString(),uploadTime.substring(0,10));
                }else{
                    devHisWaterZc.setIsEffective(0);
                }
            }else{
                return CommonResult.failed("时间设置有误请联系管理员");
            }
            devHisWaterZc.setFuheTime(new Date());
            String imgFiles = devHisWaterZc.getImgFiles();
            if(null !=imgFiles && StringUtils.isNotBlank(imgFiles)){
                List<String> imgFilesList = Arrays.asList(imgFiles.split(","));
                for (String imgFile : imgFilesList) {
                    DevHisFiles devHisFiles = new DevHisFiles();
                    devHisFiles.setId(UUIDUtils.get32UUID());
                    devHisFiles.setDevhisId(devHisWaterZc.getId().toString());
                    devHisFiles.setFiledId(imgFile);
                    devHisFiles.setSpareFiled(devHisWaterZc.getTableType());
                    if("1".equals(devHisWaterZc.getTableType())){
                        devHisFiles.setTableName(tableName);
                    }
                    if("2".equals(devHisWaterZc.getTableType())){
                        devHisFiles.setTableName(tableName);
                    }
                    int insert = devHisFilesService.insert(devHisFiles);
                }
            }
            if("1".equals(devHisWaterZc.getTableType()) ){
                devHisWaterService.updateWater(devHisWaterZc,tableName);
            }
            if("2".equals(devHisWaterZc.getTableType()) ){
                devHisZcService.updateZc(devHisWaterZc,tableName);
            }
            devHisResultService.saveOne(7,user.getEnterpriseId().toString(),uploadTime.substring(0,10));
            return CommonResult.success("复核成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            return CommonResult.failed("添加失败，请联系管理员");
        }
    }
    /**
     * 获取图片
     *
     */
    @AutoLog(value = "获取复核图片")
    @ApiOperation(value = "获取复核图片", notes = "获取复核图片")
    @GetMapping("/getImgs/{id}/{tableType}/{tableName}")
    public CommonResult getImgs(@PathVariable("id") String id,@PathVariable("tableType") String tableType,@PathVariable("tableName") String tableName) {
        try {
        /*    String tableIndex=null;
            String tableName=null;
            if(StringUtils.isNotBlank(sj)){
                String[] strings = sj.split(",");
                String beginDate=strings[0];
                tableName=tableName+DateUtil.getWeek(beginDate);
            }else{
                tableIndex = DateUtil.getYearWeek();
            }
            if("1".equals(tableType)){
                tableName="dev_his_water_"+tableIndex;
            }
            if("2".equals(tableType)){
                tableName="dev_his_zc_"+tableIndex;
            }*/
            List<DataFiles> filesList=devHisFilesService.getImgsByHisId(id,tableType,tableName);
            return CommonResult.success(filesList);
        } catch (Exception e) {
            log.error(e.getMessage());
            return CommonResult.failed("查询失败，请联系管理员");
        }
    }
}
